package com.net.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * api请求过滤器
 * 
 * @author 尚业
 *
 */
public class LoginFilter implements Filter {
	private Logger logger = Logger.getLogger(LoginFilter.class);
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO 自动生成的方法存根

	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String[] notFilter = new String[] {"register","login"};// 过滤字段、路径。。。。。。
		String urlPath = request.getServletPath();
		Boolean flg = false;
		for (String url : notFilter) {
			if ((urlPath.contains(url))) {
				flg = true;
			}
		}
		if (flg) {
			chain.doFilter(req, res);
		} else {
			HttpSession session = request.getSession();
			String UID = (String) session.getAttribute("SESSIONID"); // 登录成功将登录ID放入session中，这里将session取出对比
			if (null == UID || "".equals(UID)) {
				logger.warn("用户登录超时或未登录，请重新登录！");
				java.io.PrintWriter out = response.getWriter();
				out.println("<html>");
				out.println("<script>");
				out.println("window.open (‘WEB-INF/pages/outTime.jsp‘,‘_top‘)");
				out.println("</script>");
				out.println("</html>");
				return;

			} else {
				chain.doFilter(req, res);
			}
		}

	}

	public void destroy() {
		// TODO 自动生成的方法存根

	}

}
